import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import 'class/controller/category_page.dart';
import 'msg/controller/message_page.dart';
import 'home/homeController/home_page.dart';
import 'order/controller/order_page.dart';
import 'mine/controller/profile_page.dart';
import 'package:ninetyfour/manger/global_config.dart';
import 'manger/location_utils.dart';
// import 'services/logger_service.dart';
import 'services/home_info_manager.dart';
import 'manger/user_manger.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_line_sdk/flutter_line_sdk.dart';

import '../services/global_state.dart';
import 'package:provider/provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:app_settings/app_settings.dart';
import 'package:flutter/services.dart';
import 'package:device_info_plus/device_info_plus.dart';
import '../../login/controller/login_view.dart';
import 'manger/umevent_utils.dart';
import 'manger/app_fonts.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  LocationManager.getAndStoreLocationData();

  final manager = HomeInfoManager();
  await manager.loadInfoData();
  await manager.loadInitData();

  if (UserInfos.shared.token.isNotEmpty) {
    UserInfos.shared.checkAccount();
  }

  LineSDK.instance.setup('2006582031').then((_) {
  });

  runApp(
    ChangeNotifierProvider(
      create: (_) => GlobalState(),
      child: MyApp(),
    ),
  );
}

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      context,
      designSize: const Size(375, 812), // 设计稿尺寸
    );
    return MaterialApp(
      navigatorObservers: [routeObserver],
      title: '94LIVES',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: GlobalConfig.mainBgColor,
        fontFamily: AppFonts.defaultFont,
      ),
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales(),
      home: const SplashScreen(),  // 启动时显示启动页
    );
  }
}

/// 启动页
class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  _SplashScreenState createState() => _SplashScreenState();
}


class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    initPush();
    Future.delayed(const Duration(seconds: 2), () {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const MainPage()),
      );
    });
  }

  Future<void> initPush() async {
    final ok = await _requestNotificationPermission();
    if (ok) {
      try {
        final token = await MethodChannel('umeng_push').invokeMethod<String>('register');
        debugPrint('UMeng deviceToken: $token');
      } catch (e) {
        debugPrint('UMeng register failed: $e');
      } 
    }
  }

  /// 请求通知栏权限
  Future<bool> _requestNotificationPermission() async {
    // 低于 Android 13 不需要
    if (!Platform.isAndroid) return true;

    // 获取 Android 版本
    final deviceInfo = DeviceInfoPlugin();
    final androidInfo = await deviceInfo.androidInfo;
    final sdkInt = androidInfo.version.sdkInt;

    // Android 13 及以上才需要请求
    if (sdkInt < 33) return true;

    var status = await Permission.notification.status;
    if (status.isDenied) {
      status = await Permission.notification.request();
    }

    // 永久拒绝 → 引导到系统设置
    if (status.isPermanentlyDenied) {
      AppSettings.openAppSettings();// 调用系统通知设置
    }
    return status.isGranted;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/qidong2.png'),
                fit: BoxFit.cover, // 适配全屏
              ),
            ),
          ),
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'assets/images/applogo.png',
                  width: 100,
                  height: 100,
                ),
                const SizedBox(height: 15),
                const Text(
                  '94LIVES',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

/// 主界面（带有 TabBar）
class MainPage extends StatefulWidget {
  final int initialIndex;
  const MainPage({super.key, this.initialIndex = 0});

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin {
  late int _currentIndex;
  late PageController _pageController; // ✅ PageController 控制页面切换

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex; // ✅ 使用传入的 initialIndex 初始化
    _pageController = PageController(initialPage: _currentIndex); // ✅ 只初始化首页

  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;
    
    return Scaffold(
      body: PageView(
        controller: _pageController,
        physics: NeverScrollableScrollPhysics(), // ✅ 禁止手势滑动，只能通过 BottomNavigationBar 切换
        children: [
          HomePage(),     // ✅ 只初始化当前页，切换后才加载
          CategoryPage(),
          MessagePage(),
          OrderPage(),
          ProfilePage(),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          if ([2, 3, 4].contains(index) && UserInfos.shared.token.isEmpty){
            WidgetsBinding.instance.addPostFrameCallback((_) {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const LoginView()),
              );
            });
            return;
          }
          // 记录底部导航点击事件
          final eventName = ['home_launch', 'category_menu_click', 'info_menu_click', 'order_menu_click', 'my_menu_click'][index];
          final customValue = ['首页打开', '点击分类菜单', '点击信息菜单', '点击订单菜单', '点击我的菜单'][index];
          UmengEvent.trackEvent(eventName, customValue, '');
          
          setState(() {
            _currentIndex = index;
            _pageController.jumpToPage(index);
          });
        },
        type: BottomNavigationBarType.fixed,
        selectedItemColor: GlobalConfig.titleSelectColor,
        unselectedItemColor: GlobalConfig.label3Color,
        selectedLabelStyle: TextStyle(fontSize: 11),
        unselectedLabelStyle: TextStyle(fontSize: 11),
        items: [
          BottomNavigationBarItem(
            icon: Image.asset(
              _currentIndex == 0
                  ? 'assets/images/shouye_selected.png'
                  : 'assets/images/shouye.png',
              width: 24,
              height: 24,
            ),
            label: localizations.home,
          ),
          BottomNavigationBarItem(
            icon: Image.asset(
              _currentIndex == 1
                  ? 'assets/images/fenlei_selected.png'
                  : 'assets/images/fenlei.png',
              width: 24,
              height: 24,
            ),
            label: localizations.category,
          ),
          BottomNavigationBarItem(
              icon: Stack(
                clipBehavior: Clip.none,
                children: [
                  Image.asset(
                    _currentIndex == 2
                        ? 'assets/images/xinxi_selected.png'
                        : 'assets/images/xinxi.png',
                    width: 24,
                    height: 24,
                  ),
                  Positioned(
                  right: -10,
                  top: -5,
                  child: Consumer<GlobalState>(
                    builder: (context, globalState, child) {
                      if (globalState.messageCount == 0) {
                        return SizedBox.shrink();
                      }
                      return Container(
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        constraints: BoxConstraints(
                          minWidth: 20,
                          minHeight: 20,
                          maxWidth: 20,
                          maxHeight: 20,
                        ),
                        child: Text(
                          globalState.messageCount.toString(),
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 11,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      );
                    },
                  ),
                ),     
                ],
              ),
            label: localizations.message,
          ),
          BottomNavigationBarItem(
            icon: Image.asset(
              _currentIndex == 3
                  ? 'assets/images/dingdan_selected.png'
                  : 'assets/images/dingdan.png',
              width: 24,
              height: 24,
            ),
            label: localizations.order,
          ),
          BottomNavigationBarItem(
              icon: Stack(
                clipBehavior: Clip.none,
                children: [
                  Image.asset(
                    _currentIndex == 4
                        ? 'assets/images/wode_selected.png'
                        : 'assets/images/wode.png',
                    width: 24,
                    height: 24,
                  ),
                  Positioned(
                  right: -10,
                  top: -5,
                  child: Consumer<GlobalState>(
                    builder: (context, globalState, child) {
                      if (globalState.notificationCount == 0) {
                        return SizedBox.shrink();
                      }
                      return Container(
                        alignment: Alignment.center,  // 确保子元素居中
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        constraints: BoxConstraints(
                          minWidth: 20,
                          minHeight: 20,
                          maxWidth: 20,
                          maxHeight: 20,
                        ),
                        child: Text(
                          globalState.notificationCount.toString(),
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 11,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      );
                    
                    },
                  ),
                ),

                ],
              ),
            label: localizations.profile,
          ),
        ],
      ),
    );
  }
}